import 'package:app/components/appBar/index.dart';
import 'package:app/components/form/FormItem.dart';
import 'package:app/components/form/index.dart';
import 'package:app/components/group/index.dart';
import 'package:app/components/layout/horizontal.dart';
import 'package:app/components/layout/horizontalItem.dart';
import 'package:app/components/layout/listTitle.dart';
import 'package:app/components/list/index.dart';
import 'package:app/components/success/index.dart';
import 'package:flutter/material.dart';

import '../../api/station-updates/index.dart';
import '../../components/button/index.dart';
import '../../components/confirm/index.dart';
import '../../util/StringUtils.dart';

class StationUpdates extends StatefulWidget {
  const StationUpdates({
    super.key,
  });

  @override
  State<StationUpdates> createState() => _StationUpdates();
}

class _StationUpdates extends State<StationUpdates> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  String _station = '';

  String _container = '';

  @override
  void initState() {
    super.initState();
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void setValue(String key, String value) {
    switch (key) {
      case '_station':
        _station = value;
        break;
      case '_container':
        _container = value;
        break;
      default:
        throw Exception("key error");
    }
  }

  void clear() {
    setState(() {
      _station = "";
      _container = "";
      _list = [];
    });
  }

  void clearList() {
    setState(() {
      _list = [];
    });
  }

  List<dynamic> _list = [];

  void search() {
    // Forms.validate(_formKey!).then((valid) async {
    //   if (valid) {
    clearList();
    if (StringUtils.isNotNull(_station) && StringUtils.isNull(_container)) {
      StationUpdatesApi.of(context).getStationItem(_station).then((res) {
        if (StringUtils.isNotNull(res.data)) {
          setState(() {
            _list = res.data
                .map((item) => {
                      'container': item['container'],
                      'itemCode': item['itemCode'],
                      'itemName': item['itemName'],
                      'itemQty': item['itemQty'].toString(),
                    })
                .toList();
            print(_list);
          });
          hideKeyBorder();
        }
      });
    } else if (StringUtils.isNull(_station) &&
        StringUtils.isNotNull(_container)) {
      StationUpdatesApi.of(context).getContainerItem(_container).then((res) {
        if (StringUtils.isNotNull(res.data)) {
          setState(() {
            _list = res.data
                .map((item) => {
                      'container': item['container'],
                      'itemCode': item['itemCode'],
                      'itemName': item['itemName'],
                      'itemQty': item['itemQty'].toString(),
                    })
                .toList();
            print(_list);
          });
          hideKeyBorder();
        }
      });
    } else {
      StationUpdatesApi.of(context).getItem(_station, _container).then((res) {
        if (StringUtils.isNotNull(res.data)) {
          setState(() {
            _list = res.data
                .map((item) => {
                      'container': item['container'],
                      'itemCode': item['itemCode'],
                      'itemName': item['itemName'],
                      'itemQty': item['itemQty'].toString(),
                    })
                .toList();
            print(_list);
          });
          hideKeyBorder();
        }
      });
    }
    //   }    // });
  }

  void clearStation() {
    if (StringUtils.isNull(_station)) {
      Confirm.of(context).show('请扫描站点码', () {
        Navigator.of(context).pop();
      });
      return;
    }
    Confirm.of(context).show('确定要清空站点吗？', () {
      Navigator.of(context).pop();
      StationUpdatesApi.of(context).clearStation(_station).then((res) {
        if (res.data) {
          Success.of(context).show('清空站点成功');
          search();
        }
      });
    });
  }

  void clearContainer() {
    if (StringUtils.isNull(_container)) {
      Confirm.of(context).show('请扫描托盘号', () {
        Navigator.of(context).pop();
      });
      return;
    }
    Confirm.of(context).show('确定要清空托盘吗？', () {
      Navigator.of(context).pop();
      StationUpdatesApi.of(context).clearContainer(_container).then((res) {
        if (res.data) {
          Success.of(context).show('清空托盘成功');
          search();
        }
      });
    });
  }

  void updateStationContainer() {
    if (StringUtils.isNull(_station)) {
      Confirm.of(context).show('请扫描站点码', () {
        Navigator.of(context).pop();
      });
      return;
    }
    if (StringUtils.isNull(_container)) {
      Confirm.of(context).show('请扫描托盘号', () {
        Navigator.of(context).pop();
      });
      return;
    }
    Confirm.of(context).show('确定要进行站点更新吗？', () {
      Navigator.of(context).pop();
      StationUpdatesApi.of(context).updateStationContainer(
          {'container': _container, 'station': _station}).then((res) {
        if (res.data) {
          Success.of(context).show('站点更新成功');
          search();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(
        context: context,
        title: '站点更新',
      ),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Group(
              context: context,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Forms(formKey: _formKey, formItem: [
                    FormItem(
                      type: 'input',
                      labelText: '站点码',
                      placeholder: '请扫描站点码',
                      filedName: 'station',
                      value: _station,
                      onEntry: (value) => search(),
                      onChange: (value) => setState(() {
                        setValue('_station', value);
                      }),
                      rules: const {
                        'station': [
                          {'required': true, 'message': '站点码不能为空'}
                        ]
                      },
                    ),
                    FormItem(
                      type: 'input',
                      labelText: '托盘号',
                      placeholder: '请扫描托盘号',
                      filedName: 'container',
                      value: _container,
                      onEntry: (value) => search(),
                      onChange: (value) => setState(() {
                        setValue('_container', value);
                      }),
                      rules: const {
                        'container': [
                          {'required': true, 'message': '托盘号不能为空'}
                        ]
                      },
                    ),
                  ]),
                  Padding(
                    padding: const EdgeInsets.only(top: 10, right: 10),
                    child: Button(
                      label: '清除',
                      icon: Icons.delete_forever,
                      onPressed: clear,
                      fontColor: Colors.black,
                      backgroundColor: Colors.white,
                      borderColor: const Color.fromARGB(255, 133, 133, 133),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListContainer(
                title: '站点物料清单：',
                length: _list.length,
                children: (index) {
                  return [
                    ListTitle(
                      context: context,
                      label: _list[index]['itemName'],
                    ),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '物料编码：',
                        value: _list[index]['itemCode'],

                      ),
                      HorizontalItem(
                        label: '数量：',
                        value: _list[index]['itemQty'],
                        valueBackground: Colors.lightBlueAccent,
                        fontColor: Colors.white,
                      ),
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '托  盘  号：',
                        value: _list[index]['container'],
                        valueBackground: Colors.green,
                        fontColor: Colors.white,
                      ),
                    ]),
                  ];
                },
              ),
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
              child: Padding(
                padding: const EdgeInsets.only(),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Button(
                        onPressed: clearStation,
                        label: '清空站点',
                        height: 60,
                        fontSize: 18,
                      ),
                    ),
                    Expanded(
                        child: Button(
                      onPressed: clearContainer,
                      label: '清空托盘',
                      height: 60,
                      fontSize: 18,
                    ))
                  ],
                ),
              ),
            ),
            SizedBox(
              width: MediaQuery.of(context).size.width,
              child: Padding(
                padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                child: Button(
                  onPressed: updateStationContainer,
                  label: '站点更新',
                  height: 60,
                  fontSize: 18,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
